import { Module } from "vuex";
import { getAsyncRouterMap } from "@/api/sign";
import routerMap from "@/routes/routes";

/** 根据店铺模式渲染不同路由 */
// const filterRoutes = (routes, mode: "mall" | "group") => {
//   return routes.filter(route => {
//     const displayCondition = route => {
//       const { meta } = route;
//       if (!meta || !meta.mode) return true;
//       if (meta.mode) return meta.mode === mode;
//       return true;
//     };

//     if (route.children) {
//       route.children = route.children.filter(displayCondition);
//     }

//     return displayCondition(route);
//   });
// };

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function addRouter(asyncRouterMap, roles) {
  roles.forEach((item1, index1) => {
    if (!item1.meta.ishow && item1.children && item1.children.length) {
      item1.children.forEach((item2, index2) => {
        if (item2.hasOwnProperty("show") && item2.show) {
          try {
            const route = asyncRouterMap[index1][`children`][index2];
            item2.show = route && route.show;
          } catch (err) {
            item2.show = true;
          }
        }
      });
    }
  });
  return roles;
}

const modules: Module<any, any> = {
  namespaced: true,
  state: {
    routersId: "",
    routers: [],
    addRouters: [], // 后期用
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.routers = routers;
    },
    SET_ROUTERS_ID: (state, id) => {
      state.routersId = id;
    },
  },
  actions: {
    // 获取用户目录
    getInfo() {
      return new Promise(resolve => {
        getAsyncRouterMap().then(res => {
          const data = res.data;
          resolve(data);
        });
      });
    },
    generateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { roles } = data;
        console.log('roles', roles)
        const accessedRouters = !!roles ? addRouter(JSON.parse(roles.properties), routerMap) : routerMap
        commit(
          "SET_ROUTERS",
          accessedRouters,
        );

        commit("SET_ROUTERS_ID", !!roles ? roles.id : "");
        resolve();
      });
    },
  },
};
export default modules;
